const Category = require('../models/Category');

exports.create = async (req, res) => {
  try {
    const { name } = req.body;
    const category = await Category.create({ name });
    res.json({ msg: '分类创建成功', category });
  } catch (err) {
    res.status(500).json({ msg: '分类创建失败', err });
  }
};

// 分页+搜索
exports.list = async (req, res) => {
  try {
    const page = parseInt(req.query.page, 10) || 1;
    const pageSize = parseInt(req.query.pageSize, 10) || 10;
    const keyword = req.query.keyword || '';
    const where = keyword
      ? { name: { [Category.sequelize.Op.like]: `%${keyword}%` } }
      : {};
    const { count, rows } = await Category.findAndCountAll({
      where,
      offset: (page - 1) * pageSize,
      limit: pageSize,
      order: [['created_at', 'DESC']]
    });
    res.json({ total: count, list: rows });
  } catch (err) {
    res.status(500).json({ msg: '获取分类失败', err });
  }
};

exports.update = async (req, res) => {
  try {
    const { id } = req.params;
    const { name } = req.body;
    const category = await Category.findByPk(id);
    if (!category) return res.status(404).json({ msg: '分类不存在' });
    category.name = name;
    await category.save();
    res.json({ msg: '分类更新成功', category });
  } catch (err) {
    res.status(500).json({ msg: '分类更新失败', err });
  }
};

exports.remove = async (req, res) => {
  try {
    const { id } = req.params;
    const category = await Category.findByPk(id);
    if (!category) return res.status(404).json({ msg: '分类不存在' });
    await category.destroy();
    res.json({ msg: '分类删除成功' });
  } catch (err) {
    res.status(500).json({ msg: '分类删除失败', err });
  }
};
